package com.witsight.platform.util.random;

import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**   
 * 说明：生成36位主键信息 
 * @Title: GenerationUUID.java 
 * @Package com.witsight.platform.util.random 
 * @See: {@link UUID}
 * Copyright: Copyright (c) 2017
 * Company:sany huax witsight team by product
 * @author: penght  
 * @date: 2017年9月11日 下午3:07:24 
 * @version: V1.0
 *
 */
public abstract class GenerationUUID {
	/**
	 * 说明：定义后能再同一类中使用static常量log
	 */
	private static final Logger log = LoggerFactory.getLogger(GenerationUUID.class);
	/**
	 * 说明：定义受保护实例count并赋值0
	 */
	protected static int count = 0;
	/**
	 * 说明：实例化对象chars
	 */
	private static final String[] chars = new String[] { "a", "b", "c", "d", "e", "f", "g", "h",
			"i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y",
			"z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F",
			"G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W",
			"X", "Y", "Z" };

	/**
	 * 说明：生成36位主键信息，线程都共享
	 * @Title: getGenerationUUID
	 * @See:
	 * @author tangheng
	 * @return 36位主键信息
	 * @date: 2015年4月29日 下午3:01:59
	 */
	public static synchronized String getGenerationUUID() {
		count++;
		long time = System.currentTimeMillis();
		String timePattern = Long.toHexString(time);
		if (log.isDebugEnabled()) {
			log.debug("timePattern : {}", timePattern);
		}
		int leftBit = 14 - timePattern.length();
		if (leftBit > 0) {
			timePattern = "0000000000".substring(0, leftBit) + timePattern;
		}
		String uuid = timePattern + Long.toHexString(Double.doubleToLongBits(Math.random()))
				+ Long.toHexString(Double.doubleToLongBits(Math.random())) + "000000000000000000";
		uuid = uuid.substring(0, 36).toUpperCase();
		return uuid;
	}

	/**
	 * 说明：生成唯一序列号 Guid
	 * @Title: generateShortGUID
	 * @See:
	 * @author tangheng
	 * @param digit   位数 1到8
	 * @return 编译后的序列号
	 * @date: 2015年4月22日 下午1:37:33
	 */
	public static final synchronized String generateShortGUID(Integer digit) {
		StringBuffer shortBuffer = new StringBuffer();
		String uuid = UUID.randomUUID().toString().replace("-", "");
		if (digit == null || digit <= 0) {
			digit = 32;
		}
		for (int i = 0; i < digit; i++) {
			String str = uuid.substring(i * 4, i * 4 + 4);
			int x = Integer.parseInt(str, 16);
			shortBuffer.append(chars[x % 0x3E]);
		}
		return shortBuffer.toString();
	}

	/**
	 * 说明：基于JAVA生成GUID的实现方法
	 * @Title: generateGUID
	 * @See:
	 * @author tangheng
	 * @return GUID
	 * @date: 2015年4月22日 下午2:22:00
	 */
	public static final synchronized String generateGUID() {
		UUID guid = UUID.randomUUID();
		return guid.toString();
	}
}
